package com.luge.model.download;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.luge.base.Base;
import com.luge.utils.FileManager;

@SuppressLint("HandlerLeak")
public class CallBackImageDown {
	private static ExecutorService executorService = Executors
			.newFixedThreadPool(3);

	private String imageUrl;
	private String filePath;
	private Handler handler;
	private CallBackInterface downInterface;

	public CallBackImageDown(String urlStr,
			CallBackInterface callBackImageDownInterface) {
		this.imageUrl = urlStr;
		this.downInterface = callBackImageDownInterface;
		this.handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					if (downInterface != null) {
						downInterface.fail();
					}
					break;
				case 1:
					try {
						Bitmap bitmap = BitmapFactory.decodeFile(filePath);
						if (downInterface != null) {
							if (bitmap == null) {
								downInterface.fail();
							} else {
								downInterface.success(bitmap);
							}
						}
					} catch (OutOfMemoryError e) {

					}
					break;
				default:
					break;
				}

			}
		};
		downLoad();
	}

	private void downLoad() {
		if (imageUrl == null || !imageUrl.contains(".")) {
			handler.sendEmptyMessage(0);
		} else if (imageUrl.contains(Environment.getExternalStorageDirectory()
				.toString())) {
			filePath = imageUrl;
			handler.sendEmptyMessage(1);
		} else {
			filePath = getFileName(imageUrl);
			if (FileManager.getInstance().isFileExist(filePath)) {
				handler.sendEmptyMessage(1);
			} else {
				executorService.submit(new Runnable() {
					@Override
					public void run() {
						try {
							FileManager mFileManager = FileManager
									.getInstance();
							if (mFileManager.downloadImgFromUrl(
									Base.cache_path, filePath, imageUrl)) {
								handler.sendEmptyMessage(1);
							} else {
								handler.sendEmptyMessage(0);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		}
	}

	private String getFileName(String imageUrl) {
		String fileName = Base.cache_path
				+ imageUrl.substring(imageUrl.lastIndexOf("/") + 1,
						imageUrl.length());
		fileName = fileName.replace(Base.IMAGE_JPG, "").replace(Base.IMAGE_PNG,
				"");
		return fileName;
	}

	public interface CallBackInterface {
		void success(Bitmap bitmap);

		void fail();
	}
}
